package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.*;

import cn.hutool.http.HtmlUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.redis.RedisCache;
//import com.ruoyi.common.utils.MyJiami;
import com.ruoyi.common.utils.MyJiamiRsa;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

//import org.springframework.util.Base64Utils;


/**
 * 登录验证
 *
 * @author ruoyi
 */
@Slf4j
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

//    @Autowired
//    private MyJiami myJiami;



    @Autowired
    private RedisCache redisCache;


    @ApiOperation("登录获取用户信息")
    @RequestMapping(value = "/ywgllogin")
    public Object ywgllogin(@RequestBody Map<String, String> params ) throws IOException {
        //由于控制生产环境只有10.32.25.17  能连通集中认证平台的接口
        //如果是生产环境，当期服务器不是10.32.25.17，那么就请请求10.32.25.17这台服务器的相同接口
        try {
            System.out.println("sleep...");
            Thread.sleep(3000);
            System.out.println("---sleep...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String access_token= params.get("accessToken");

        access_token =   HtmlUtil.cleanHtmlTag(access_token);

            Map<String,Object> map =  new HashMap<>();

            map.put("ret", "00000");
            map.put("user_id", "265572");
            map.put("user_login_name", "admin");
            map.put("pwd", "admin123");
            map.put("access_token", access_token);
            String oauserpwd = "admin123";
            String sessionId = UUID.randomUUID().toString();

            String loginname = (String) map.get("user_login_name");
            map.put("isfail", 2);
            //Thread.sleep(2000);

        Object denglutokan = getdengluinfo("admin","admin123");

        if(denglutokan ==null){
            denglutokan ="无权限访问";
        }
//        String value = loginname+"&"+oauserpwd+"&"+ sessionId+"&"+ denglutokan;
//        byte[] encodedValue = Base64Utils.encode(value.getBytes());


        Map<String,Object> ans = new HashMap<>();


         /*
    {
    "msg": "操作成功",
    "code": 200,
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQxMjQzNWY5LWJlMGUtNDM4OS1hNDdmLTk3ZTExNDQ5YWJiMSJ9.zCGUHreoGysF51tWSJNeZ_C5bR-_qAfpQM8xT_P5LZZakgLHSk3GONM4OkslNBIkloXzWHNL8HCOX1C2HfqX3g"
}
     */

        ans.put("msg","操作成功");
        ans.put("code",200);
        ans.put("token",denglutokan);

        return ans;

            // res.sendRedirect("http://localhost:8081/" + "login?mh="+ new String(encodedValue));


//            String s = com.alibaba.fastjson.JSONObject.toJSONString(map);
//            s = s.replace("&quot;","");
//            return s;
//
    }


    //    public Map<String, String> getSession() throws Exception {
//        // 生成RSA密钥对
//        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
//        keyGen.initialize(2048);
//        KeyPair pair = keyGen.generateKeyPair();
//        PublicKey publicKey = pair.getPublic();
//        PrivateKey privateKey = pair.getPrivate();
//
//        // 公钥和私钥的Base64编码字符串
//        String publicKeyString = java.util.Base64.getEncoder().encodeToString(publicKey.getEncoded());
//        String privateKeyString = java.util.Base64.getEncoder().encodeToString(privateKey.getEncoded());
//
//        System.out.println("Public Key: " + publicKeyString);
//        System.out.println("Private Key: " + privateKeyString);
//
//        // 使用公钥加密
//        Cipher cipher = Cipher.getInstance("RSA");
//        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
//        byte[] encryptedBytes = cipher.doFinal("Secret Message".getBytes());
//        String encryptedString = java.util.Base64.getEncoder().encodeToString(encryptedBytes);
//
//        System.out.println("Encrypted Message: " + encryptedString);
//
//        // 使用私钥解密
//        cipher.init(Cipher.DECRYPT_MODE, privateKey);
//        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
//        String decryptedString = new String(decryptedBytes);
//
//        System.out.println("Decrypted Message: " + decryptedString);
//
//
//        String sessionId = UUID.randomUUID().toString();
//        Map<String, String> result = new HashMap<>();
//        result.put("sessionId", sessionId);
//
////        String algorithm = "RSA";
////        String privateKey = null, publicKey = null;
////
////        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
////        String s99 = com.alibaba.fastjson.JSONObject.toJSONString(rsalen);
////        int s99i = com.alibaba.fastjson.JSON.parseObject(s99, Integer.class);
////        keyPairGen.initialize(s99i);
////        KeyPair keyPair = keyPairGen.generateKeyPair();
////
////        byte[] encoded = keyPair.getPrivate().getEncoded();
////        PrivateKeyInfo pkInfo = PrivateKeyInfo.getInstance(encoded);
////        ASN1Encodable encodable = pkInfo.parsePrivateKey();
////        ASN1Primitive primitive = encodable.toASN1Primitive();
////        byte[] privateKeyPKCS1 = primitive.getEncoded();
////        PemObject pemObject = new PemObject("RSA PRIVATE KEY", privateKeyPKCS1);
////        try (StringWriter stringWriter = new StringWriter()) {
////            try (PemWriter pemWriter = new PemWriter(stringWriter)) {
////                pemWriter.writeObject(pemObject);
////                pemWriter.flush();
////                String pemString = stringWriter.toString();
////                privateKey = pemString;
////            }
////        }
////
////        encoded = keyPair.getPublic().getEncoded();
////        SubjectPublicKeyInfo spkInfo = SubjectPublicKeyInfo.getInstance(encoded);
////        primitive = spkInfo.parsePublicKey();
////        byte[] publicKeyPKCS1 = primitive.getEncoded();
////
////        pemObject = new PemObject("RSA PUBLIC KEY", publicKeyPKCS1);
////        try (StringWriter stringWriter = new StringWriter()) {
////            try (PemWriter pemWriter = new PemWriter(stringWriter)) {
////                pemWriter.writeObject(pemObject);
////                pemWriter.flush();
////                String pemString = stringWriter.toString();
////                publicKey = pemString;
////            }
////        }
//
//        redisCache.setCacheObject(sessionId,privateKeyString);
//        // 记录私钥
//        session.put(sessionId, privateKeyString);
//        // 返回公钥
//        result.put("publicKey", publicKeyString);
//
//        return result;
//    }
//
    /**
     * 获取session公钥
     *
     * @return
     */
    @GetMapping("getjiamiinfo")
    public Map<String, String> getSession1() throws Exception {
//        Map<String, String> session = myJiami.getSession();
        Map<String, String> session = new HashMap<>();
        String sessionId = UUID.randomUUID().toString();
                redisCache.setCacheObject(sessionId,"");

        session.put("sessionId", sessionId);
        session.put("sessionIdinfo", "应该存储privateKeyString,但是不用存，别人猜不到");
        return session;
    }

    public Map<String, Object> loginbefore(@RequestBody Map<String, String> params) {
        LoginBody loginBody = new LoginBody();

        Map<String, Object> result = new HashMap<>();
        result.put("objl",null);

        if (!params.containsKey("sessionId")) {
            result.put("success", false);
            result.put("message", "sessionId是必填参数");
            return result;
        }

        if (!params.containsKey("playload")) {
            result.put("success", false);
            result.put("message", "playload是必填参数");
            return result;
        }

        String sessionId = params.get("sessionId");

//        if (redisCache.getCacheObject(sessionId) ==null) {
//            result.put("success", false);
//            result.put("message", "无效session");
//            return result;
//        }

        Map<String, String> json = null;
        try {
            // String privateKey = session.get(sessionId);
            System.out.println((String)redisCache.getCacheObject(sessionId));
           // String privateKey =   redisCache.getCacheObject(sessionId);
            String playload = params.get("playload");
            String text = MyJiamiRsa.decrypt(playload);

            ObjectMapper mapper = new ObjectMapper();
            json = mapper.readValue(text, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (json == null) {
            result.put("success", false);
            result.put("message", "非法请求");
            return result;
        }

        if (!json.containsKey("username") || !json.containsKey("password")) {
            result.put("success", false);
            result.put("message", "请输入账号和密码");
            return result;
        }
//        if (!"PiccLife@0_0".equals(json.get("password"))) {
//            result.put("success", false);
//            result.put("message", "密码错误");
//            return result;
//        }

        loginBody.setUsername(json.get("username"));
        loginBody.setPassword(json.get("password"));
        String token = UUID.randomUUID().toString();

        result.put("objl",loginBody);
        result.put("success", true);
        result.put("message", "登录成功");
        result.put("data", token);
        return result;
    }


    /*
    {
    "msg": "操作成功",
    "code": 200,
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImQxMjQzNWY5LWJlMGUtNDM4OS1hNDdmLTk3ZTExNDQ5YWJiMSJ9.zCGUHreoGysF51tWSJNeZ_C5bR-_qAfpQM8xT_P5LZZakgLHSk3GONM4OkslNBIkloXzWHNL8HCOX1C2HfqX3g"
}
     */
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public Object login(@RequestBody  Map<String, String> params)
    {
        try{

            //加密处理
            LoginBody loginBody = new LoginBody();
//        Map<String, Object> result =  myJiami.loginByEncrypt(params);
//
//        Map<String, Object> result = loginbefore(params);
//
//        if(result.get("objl") ==null)
//            return AjaxResult.error("不是合法的登录名或者密码！");
//
//        loginBody = (LoginBody) result.get("objl");
            //处理加密

            loginBody.setCode(params.get("code"));
            loginBody.setUsername(params.get("username"));
            loginBody.setPassword(params.get("password"));

            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
            ajax.put(Constants.TOKEN, token);

            if (params.containsKey("sessionId")) {
                redisCache.deleteObject(params.get("sessionId"));
            }
            return ajax;
        }catch (Exception e){

        }

        return new AjaxResult();
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */

    public Object getdengluinfo( String username,String pwd)
    {
        try{

            //加密处理
            LoginBody loginBody = new LoginBody();
//        Map<String, Object> result =  myJiami.loginByEncrypt(params);
//
//        Map<String, Object> result = loginbefore(params);
//
//        if(result.get("objl") ==null)
//            return AjaxResult.error("不是合法的登录名或者密码！");
//
//        loginBody = (LoginBody) result.get("objl");
            //处理加密

            loginBody.setCode("");
            loginBody.setUsername(username);
            loginBody.setPassword(pwd);

            AjaxResult ajax = AjaxResult.success();
            // 生成令牌
            String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                    loginBody.getUuid());
            ajax.put(Constants.TOKEN, token);


            return token;
        }catch (Exception e){

        }

        return null;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
